package com.wing.light.readexcel;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import sun.swing.FilePane;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {
	private String filePath = "";

	public static void main(String args[]) throws Throwable {
		URL url = new URL("file:/c:/cars.xls");
		ReadExcel getURLExcel = new ReadExcel(url);
		File f = new File(getURLExcel.getFilePath());
		String s = getURLExcel.readExcel(f);
		System.out.println(s);
	}

	public ReadExcel(URL url) {
		String temp = url.getFile();
		temp = temp.substring(1);
		filePath = temp.replace("/", "\\\\");
	}

	public String getFilePath() {
		return filePath;
	}

	public String urlToPath(URL url) {
		String temp = url.getFile();
		temp = temp.substring(1).replace("/", "\\\\");
		return temp;
	}

	public String readExcel(File file) {
		StringBuffer sb = new StringBuffer();

		Workbook wb = null;
		try {
			// 构造Workbook（工作薄）对象
			wb = Workbook.getWorkbook(file);
		} catch (BiffException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (wb == null)
			return null;

		// 获得了Workbook对象之后，就可以通过它得到Sheet（工作表）对象了
		Sheet[] sheet = wb.getSheets();

		if (sheet != null && sheet.length > 0) {
			// 对每个工作表进行循环
			for (int i = 0; i < sheet.length; i++) {
				// 得到当前工作表的行数
				int rowNum = sheet[i].getRows();
				for (int j = 0; j < rowNum; j++) {
					// 得到当前行的所有单元格
					Cell[] cells = sheet[i].getRow(j);
					if (cells != null && cells.length > 0) {
						System.out.println(cells.length);
						// 对每个单元格进行循环
						for (int k = 0; k < cells.length; k++) {
							// 读取当前单元格的值
							//System.out.println(cells[k].getType().toString());
							if (isNumber(cells[k])) {
								String cellValue = cells[k].getContents();
//								System.out.print(cellValue+", ");
//								sb.append(cellValue + "\t");
							}
						}
					}
					sb.append("\r\n");
				}
				sb.append("\r\n");
			}
		}
		// 最后关闭资源，释放内存
		wb.close();
		return sb.toString();
	}

	public boolean isNumber(Cell cell) {
		boolean flag = false;
		if (!cell.getType().toString().equalsIgnoreCase("EMPTY")) {
			String cellValue = cell.getContents();
			for (int i = cellValue.length(); --i >= 0;) {
				if (!Character.isDigit(cellValue.charAt(i))) {
					return false;
				}
			}
			return true;
		}
		return flag;
	}
}